<template>
  <div class="course-detail-container">
    <el-row :gutter="20">
      <!-- 左侧课程信息 -->
      <el-col :span="16">
        <el-card class="course-info-card">
          <template #header>
            <div class="card-header">
              <h2>{{ course.title }}</h2>
              <div class="course-actions">
                <el-button
                  v-if="enrollment && enrollment.enrollmentStatus === 'COMPLETED'"
                  type="success"
                  disabled
                >
                  已完成
                </el-button>
                <el-button
                  v-else-if="enrollment && enrollment.enrollmentStatus === 'APPROVED'"
                  type="primary"
                  @click="startLearning"
                >
                  {{ hasStartedLearning ? '继续学习' : '开始学习' }}
                </el-button>
                <el-button
                  v-else-if="enrollment && enrollment.enrollmentStatus === 'PENDING'"
                  type="warning"
                  disabled
                >
                  审查中
                </el-button>
                <el-button
                  v-else
                  type="primary"
                  @click="enrollCourseDetail"
                >
                  报名学习
                </el-button>
              </div>
            </div>
          </template>

          <div class="course-cover">
            <img
              v-if="course.coverImage"
              :src="course.coverImage.startsWith('http') ? course.coverImage : `${apiBaseUrl}${course.coverImage}`"
              :alt="course.title"
              class="cover-image"
              @error="handleCourseImageError"
            />
            <el-avatar v-else :size="200"><el-icon><Collection /></el-icon></el-avatar>
          </div>

          <div class="course-meta">
            <el-tag
              :type="getDifficultyTagType(course.difficultyLevel)"
              size="small"
            >
              {{ getDifficultyText(course.difficultyLevel) }}
            </el-tag>
            <span class="duration">
              <el-icon><Clock /></el-icon>
              {{ formatDuration(course.estimatedDuration) }}
            </span>
            <span class="category">
              <el-icon><Folder /></el-icon>
              {{ course.category }} / {{ course.subcategory }}
            </span>
          </div>

          <div class="course-description">
            <h3>课程介绍</h3>
            <p>{{ course.description }}</p>
          </div>

          <div class="course-tags" v-if="course.tags && course.tags.length > 0">
            <el-tag
              v-for="tag in course.tags"
              :key="tag"
              type="info"
              size="small"
            >
              {{ tag }}
            </el-tag>
          </div>
        </el-card>

        <!-- 课程大纲 -->
        <el-card class="course-outline-card">
          <template #header>
            <h3>课程大纲</h3>
          </template>

          <div class="modules-list" v-if="modules.length > 0 || courseVideos.length > 0">
            <!-- 模块和课时 -->
            <div
              v-for="module in modules"
              :key="module.id"
              class="module-item"
            >
              <div class="module-header">
                <h4>{{ module.title }}</h4>
                <p>{{ module.description }}</p>
              </div>

              <div class="lessons-list">
                <div
                  v-for="lesson in getLessonsByModule(module.id)"
                  :key="lesson.id"
                  class="lesson-item"
                  :class="{ 'disabled': !enrollment || enrollment.enrollmentStatus !== 'APPROVED' }"
                  @click="(!enrollment || enrollment.enrollmentStatus !== 'APPROVED') ? showEnrollmentRequiredMessage() : startLearning()"
                >
                  <div class="lesson-info">
                    <el-icon>
                      <VideoPlay v-if="lesson.lessonType === 'VIDEO'" />
                      <Document v-if="lesson.lessonType === 'DOCUMENT'" />
                      <Reading v-if="lesson.lessonType === 'TEXT'" />
                    </el-icon>
                    <span class="lesson-title">{{ lesson.title }}</span>
                  </div>
                  <div class="lesson-duration">
                    {{ formatDuration(lesson.estimatedDuration) }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 独立视频（不属于任何模块） -->
            <div v-if="courseVideos.length > 0" class="module-item">
              <div class="module-header">
                <h4>课程视频</h4>
                <p>本课程包含的视频内容</p>
              </div>

              <div class="lessons-list">
                <div
                  v-for="video in courseVideos"
                  :key="video.id"
                  class="lesson-item"
                  :class="{ 'disabled': !enrollment || enrollment.enrollmentStatus !== 'APPROVED' }"
                  @click="(!enrollment || enrollment.enrollmentStatus !== 'APPROVED') ? showEnrollmentRequiredMessage() : playVideo(video)"
                >
                  <div class="lesson-info">
                    <el-icon>
                      <VideoPlay />
                    </el-icon>
                    <span class="lesson-title">{{ video.title }}</span>
                  </div>
                  <div class="lesson-duration">
                    {{ formatVideoDuration(video.fileSize) }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <p v-else class="no-outline">
            暂无课程大纲
          </p>
        </el-card>
      </el-col>

      <!-- 右侧信息 -->
      <el-col :span="8">
        <!-- 学习进度 -->
        <el-card class="progress-card" v-if="enrollment">
          <template #header>
            <h3>学习进度</h3>
          </template>

          <div class="progress-info">
            <div class="progress-percentage">
              <el-progress
                type="circle"
                :percentage="enrollment.progressPercentage || 0"
                :width="120"
              />
            </div>
            <div class="progress-stats">
              <p>已完成课时: {{ enrollment.completedLessons || 0 }}/{{ enrollment.totalLessons || 0 }}</p>
              <p>报名时间: {{ formatDate(enrollment.enrollmentDate) }}</p>
              <p v-if="enrollment.completionDate">
                完成时间: {{ formatDate(enrollment.completionDate) }}
              </p>
            </div>
          </div>
        </el-card>

        <!-- 讲师信息 -->
        <el-card class="instructor-card">
          <template #header>
            <h3>讲师信息</h3>
          </template>

          <div class="instructor-info">
            <div class="instructor-avatar">
              <el-avatar :size="60">{{ course.creatorName?.charAt(0) }}</el-avatar>
            </div>
            <div class="instructor-details">
              <p class="instructor-name">{{ course.creatorName }}</p>
              <p class="instructor-role">课程讲师</p>
            </div>
          </div>
        </el-card>

        <!-- 相关问题 -->
        <el-card class="questions-card">
          <template #header>
            <div class="card-header">
              <h3>相关问题</h3>
              <div class="questions-header-actions">
                <el-button
                  type="primary"
                  size="small"
                  @click="askQuestion"
                >
                  提问
                </el-button>
                <el-button
                  size="small"
                  @click="refreshRelatedQuestions"
                >
                  刷新
                </el-button>
              </div>
            </div>
          </template>

          <div class="questions-list">
            <!-- 加载状态 -->
            <div v-if="loadingRelatedQuestions" class="loading-questions">
              <el-skeleton :rows="3" animated />
            </div>

            <!-- 问题列表 -->
            <div
              v-else
              v-for="question in relatedQuestions"
              :key="question.id"
              class="question-item"
              @click="viewQuestion(question.id)"
            >
              <p class="question-title">{{ question.title }}</p>
              <div class="question-meta">
                <span>{{ question.userName }}</span>
                <span>{{ formatDate(question.createTime) }}</span>
                <span>{{ question.answerCount }} 回答</span>
              </div>
            </div>

            <!-- 无问题提示 -->
            <p v-if="!loadingRelatedQuestions && relatedQuestions.length === 0" class="no-questions">
              暂无相关问题
              <el-link type="primary" @click="viewAllQuestions">查看所有问题</el-link>
            </p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 视频播放器模态框 -->
    <el-dialog
      v-model="showVideoPlayer"
      title="视频播放"
      width="80%"
      :before-close="closeVideoPlayer"
    >
      <VideoPlayer
        v-if="selectedVideo"
        :video="selectedVideo"
        :api-base-url="apiBaseUrl"
        @close="closeVideoPlayer"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Collection,
  Clock,
  Folder,
  VideoPlay,
  Document,
  Reading
} from '@element-plus/icons-vue'
import request from '../../utils/request'

// Import VideoPlayer component
import VideoPlayer from '../../components/VideoPlayer.vue'

// API基础URL
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'

// 路由
const route = useRoute()
const router = useRouter()

// 数据
const course = ref({
  id: 0,
  title: '',
  description: '',
  coverImage: '',
  difficultyLevel: '',
  estimatedDuration: 0,
  category: '',
  subcategory: '',
  tags: [],
  status: '',
  creatorId: 0,
  creatorName: '',
  createTime: '',
  updateTime: '',
  publishTime: ''
})

const modules = ref([])
const lessons = ref([])
const courseVideos = ref([])
const enrollment = ref(null)
const relatedQuestions = ref([])
const loadingRelatedQuestions = ref(false)
const showVideoPlayer = ref(false)
const selectedVideo = ref(null)
const hasStartedLearning = ref(false)

// 获取课程详情
const fetchCourseDetail = async () => {
  try {
    const courseId = route.params.id
    const response = await request.get(`/api/study/courses/${courseId}`)
    course.value = response.data

    // 获取课程模块和课时
    fetchCourseModules(courseId)

    // 获取课程视频
    fetchCourseVideos(courseId)

    // 获取用户报名信息
    fetchUserEnrollment(courseId)

    // 获取相关问题
    fetchRelatedQuestions(courseId)
  } catch (error) {
    console.error('获取课程详情失败:', error)
    ElMessage.error('获取课程详情失败')
  }
}

// 获取课程模块
const fetchCourseModules = async (courseId: number) => {
  try {
    const response = await request.get(`/api/study/courses/${courseId}/modules`)
    modules.value = response.data

    // 获取每个模块的课时
    for (const module of modules.value) {
      await fetchModuleLessons(module.id)
    }
  } catch (error: any) {
    if (error.response && error.response.status === 403) {
      ElMessage.error('权限不足，请先登录')
    } else {
      ElMessage.error('获取课程模块失败')
    }
  }
}

// 获取模块课时
const fetchModuleLessons = async (moduleId: number) => {
  try {
    const response = await request.get(`/api/study/courses/modules/${moduleId}/lessons`)
    lessons.value = [...lessons.value, ...response.data]
  } catch (error) {
    ElMessage.error('获取模块课时失败')
  }
}

// 获取课程视频
const fetchCourseVideos = async (courseId: number) => {
  try {
    const response = await request.get(`/api/study/videos/course/${courseId}`)
    if (response.data.success) {
      courseVideos.value = response.data.videos || []
    }
  } catch (error) {
    console.error('获取课程视频失败:', error)
  }
}

// 获取用户报名信息
const fetchUserEnrollment = async (courseId: number) => {
  try {
    const response = await request.get(`/api/study/courses/${courseId}/enrollments/check`)
    if (response.data.success) {
      enrollment.value = {
        enrolled: response.data.enrolled,
        enrollmentStatus: response.data.enrollmentStatus
      }

      // 检查用户是否已经开始学习（如果有学习进度则认为已开始学习）
      if (response.data.enrollmentStatus === 'APPROVED') {
        try {
          const progressResponse = await request.get(`/api/study/progress/courses/${courseId}/overview`)
          hasStartedLearning.value = progressResponse.data &&
            (progressResponse.data.completedLessons > 0 ||
             (progressResponse.data.lessonProgresses && progressResponse.data.lessonProgresses.length > 0))
        } catch (progressError) {
          // 如果获取学习进度失败，不影响主流程
          hasStartedLearning.value = false
        }
      }
    } else {
      enrollment.value = null
    }
  } catch (error) {
    // 用户未报名该课程或接口不可用
    enrollment.value = null
  }
}

// 获取相关问题
const fetchRelatedQuestions = async (courseId: number) => {
  loadingRelatedQuestions.value = true
  try {
    const response = await request.get(`/api/study/questions`, {
      params: {
        courseId: courseId,
        page: 0,
        size: 5
      }
    })
    relatedQuestions.value = response.data.content

    // 如果没有相关问题，给出提示
    if (relatedQuestions.value.length === 0) {
      console.log(`课程ID ${courseId} 暂无相关问题`)
    }
  } catch (error) {
    console.error('获取相关问题失败:', error)
    ElMessage.error('获取相关问题失败')
  } finally {
    loadingRelatedQuestions.value = false
  }
}

// 刷新相关问题
const refreshRelatedQuestions = () => {
  const courseId = route.params.id
  if (courseId) {
    fetchRelatedQuestions(Number(courseId))
  }
}

// 查看所有问题
const viewAllQuestions = () => {
  router.push('/study/questions')
}


// 根据模块ID获取课时
const getLessonsByModule = (moduleId: number) => {
  return lessons.value.filter((lesson: any) => lesson.moduleId === moduleId)
}

// 报名课程
const enrollCourse = async () => {
  try {
    const courseId = route.params.id
    await request.post(`/api/study/enrollments/courses/${courseId}`)
    ElMessage.success('课程报名成功')
    fetchUserEnrollment(courseId)
  } catch (error) {
    ElMessage.error('课程报名失败')
  }
}

// 开始学习
const startLearning = () => {
  const courseId = route.params.id
  router.push(`/study/learning/${courseId}`)
}

// 提问
const askQuestion = () => {
  const courseId = route.params.id
  router.push(`/study/questions/ask?courseId=${courseId}&courseTitle=${encodeURIComponent(course.value.title)}`)
}

// 查看问题
const viewQuestion = (questionId: number) => {
  router.push(`/study/questions/${questionId}`)
}

// 播放视频
const playVideo = (video: any) => {
  selectedVideo.value = video
  showVideoPlayer.value = true
}

// 关闭视频播放器
const closeVideoPlayer = () => {
  showVideoPlayer.value = false
  selectedVideo.value = null
}

// 工具方法
const getDifficultyTagType = (level: string) => {
  switch (level) {
    case 'BEGINNER':
      return 'success'
    case 'INTERMEDIATE':
      return 'warning'
    case 'ADVANCED':
      return 'danger'
    default:
      return 'info'
  }
}

const getDifficultyText = (level: string) => {
  switch (level) {
    case 'BEGINNER':
      return '初级'
    case 'INTERMEDIATE':
      return '中级'
    case 'ADVANCED':
      return '高级'
    default:
      return '未知'
  }
}

const formatDuration = (minutes: number) => {
  if (!minutes) return '未知时长'
  return `${minutes}分钟`
}

const enrollCourseDetail = async () => {
  try {
    const courseId = Number(route.params.id)
    const response = await request.post(`/api/study/courses/${courseId}/enroll`)

    if (response.data.success) {
      ElMessage.success('报名申请已提交，等待课程创建者审批')
      // 刷新报名状态
      fetchUserEnrollment(courseId)
    } else {
      ElMessage.error(response.data.message || '报名申请失败')
    }
  } catch (error) {
    console.error('报名课程失败:', error)
    ElMessage.error('报名课程失败')
  }
}

const formatVideoDuration = (fileSize: number) => {
  if (!fileSize || fileSize <= 0) return '未知时长'
  // This is a rough estimation - in a real application, you would get this from video metadata
  // Assuming average bitrate of 1 MB per minute for estimation
  const minutes = Math.round(fileSize / (1024 * 1024) / 1)
  return minutes > 0 ? `${minutes}分钟` : '未知时长'
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const showEnrollmentRequiredMessage = () => {
  if (!enrollment.value) {
    ElMessage.warning('请先报名学习该课程')
  } else if (enrollment.value.enrollmentStatus === 'PENDING') {
    ElMessage.warning('您的报名申请正在审查中，请耐心等待')
  } else if (enrollment.value.enrollmentStatus === 'REJECTED') {
    ElMessage.warning('您的报名申请已被拒绝')
  }
}

// 监听路由变化
watch(
  () => route.params.id,
  (newId, oldId) => {
    if (newId !== oldId) {
      fetchCourseDetail()
    }
  }
)

// 组件挂载时获取数据
onMounted(() => {
  fetchCourseDetail()
})
</script>

<style scoped>
.course-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-info-card {
  margin-bottom: 20px;
}

.course-cover {
  height: 300px;
  overflow: hidden;
  border-radius: 8px;
  margin-bottom: 20px;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-cover {
  width: 100%;
  height: 100%;
  background-color: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 4em;
}

.course-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.course-meta .el-tag,
.course-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.course-description h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.course-description p {
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

.course-tags {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.course-outline-card {
  margin-bottom: 20px;
}

.modules-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.module-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 15px;
}

.module-header h4 {
  margin: 0 0 5px 0;
  color: #303133;
}

.module-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.lessons-list {
  margin-top: 15px;
  padding-left: 20px;
}

.lesson-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f2f5;
}

.lesson-item:last-child {
  border-bottom: none;
}

.lesson-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.lesson-title {
  color: #606266;
}

.lesson-duration {
  font-size: 12px;
  color: #909399;
}

.lesson-item.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.lesson-item.disabled .lesson-title {
  color: #909399;
}

.progress-card {
  margin-bottom: 20px;
}

.progress-info {
  display: flex;
  gap: 20px;
  align-items: center;
}

.progress-stats {
  flex: 1;
}

.progress-stats p {
  margin: 5px 0;
  color: #606266;
}

.instructor-card {
  margin-bottom: 20px;
}

.instructor-info {
  display: flex;
  gap: 15px;
  align-items: center;
}

.instructor-avatar {
  flex-shrink: 0;
}

.instructor-details {
  flex: 1;
}

.instructor-name {
  margin: 0 0 5px 0;
  font-weight: bold;
  color: #303133;
}

.instructor-role {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.questions-card .card-header {
  justify-content: space-between;
}

.questions-header-actions {
  display: flex;
  gap: 10px;
}

.questions-list {
  max-height: 300px;
  overflow-y: auto;
}

.loading-questions {
  padding: 20px;
}

.question-item {
  padding: 10px 0;
  border-bottom: 1px solid #f0f2f5;
  cursor: pointer;
}

.question-item:last-child {
  border-bottom: none;
}

.question-item:hover {
  background-color: #f5f7fa;
}

.question-title {
  margin: 0 0 5px 0;
  color: #303133;
  font-size: 14px;
}

.question-meta {
  display: flex;
  gap: 10px;
  font-size: 12px;
  color: #909399;
}

.no-questions {
  text-align: center;
  color: #909399;
  margin: 20px 0;
}
</style>
